﻿using SuperiorShopBussinessService;
using System;
using System.Linq;
using System.Web.Mvc;
using SuperiorModel;
using SuperiorCommon;
using Redis;

namespace SuperiorShopkeeper.Controllers
{
    [JsonException]
    [CheckLoginFitler]
    public class ProductController : BaseController
    {
        private readonly IProductService _IProductService;
        private readonly ISetService _ISetService;

        public ProductController(IProductService IProductService, ISetService ISetService)
        {
            _IProductService = IProductService;
            _ISetService = ISetService;
        }
        protected override void Dispose(bool disposin)
        {
            this._IProductService.Dispose();
            this._ISetService.Dispose();
            base.Dispose(disposin);
        }

        // GET: Product
        public ActionResult Index()
        {
            return View();
        }
        [ShopAuthority(AuthorityMenuEnum.ProductMenu)]
        public ActionResult Menu()
        {
            var model = _IProductService.MenuList(UserContext.DeSecretId.ToInt());
            return View(model);
        }
        /// <summary>
        /// 添加分类
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [AjaxOnly]
        [HttpPost]
        [ShopAuthority(AuthorityOptionEnum.AddMenu)]
        public JsonResult AddMenu(MenuModel model)
        {
            if (!ModelState.IsValid)
                return Error(base.ErrorMsg());
            //将分类图上传的图片服务器
            if (!UploadService.Upload(model.ImgPath, UploaderKeys.ProductMenu))
                return Error("上传图片失败");
            string msg = "";
            model.ShopAdminId = UserContext.DeSecretId.ToInt();
            var ret = _IProductService.AddMenu(model, out msg);
            if (ret != 1)
                return Error(msg);
            RedisManager.Remove("GetMenuList_" + model.ShopAdminId);
            return Success(true);
        }
        /// <summary>
        /// 修改分类
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [AjaxOnly]
        [HttpPost]
        [ShopAuthority(AuthorityOptionEnum.EditMenu)]
        public JsonResult EditMenu(MenuModel model)
        {
            if (!ModelState.IsValid)
                return Error(base.ErrorMsg());
            model.Id = model.Id;
            if (model.Id == 0)
                return Error("非法参数");
            //如果图片地址包括后台网关，就从新上传
            if (model.ImgPath.Contains(ConfigSettings.Instance.AdminImageHost))
            {
                if (!UploadService.Upload(model.ImgPath, UploaderKeys.ProductMenu))
                    return Error("上传图片失败");
            }
            string msg = "";
            model.ShopAdminId = UserContext.DeSecretId.ToInt();
            var ret = _IProductService.EditMenu(model, out msg);
            if (ret != 1)
                return Error(msg);
            RedisManager.Remove("GetMenuList_" + model.ShopAdminId);
            return Success(true);
        }
        /// <summary>
        /// 分类上下架
        /// </summary>
        /// <param name="id"></param>
        /// <param name="optionStatus"></param>
        /// <returns></returns>
        [AjaxOnly]
        [ShopAuthority(AuthorityOptionEnum.OptionMenu)]
        public JsonResult OptionMenu(int id, int optionStatus)
        {
            string msg = "";
            int shopAdminId = UserContext.DeSecretId.ToInt();
            var ret = _IProductService.OptionMenu(id, optionStatus, shopAdminId, out msg);
            if (ret != 1)
                return Error(msg);
            RedisManager.Remove("GetMenuList_" + shopAdminId);
            return Success(true);
        }
        /// <summary>
        /// 删除分类
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [AjaxOnly]
        [ShopAuthority(AuthorityOptionEnum.DeleteMenu)]
        public JsonResult DeleteMenu(int id)
        {
            string msg = "";
            int shopAdminId = UserContext.DeSecretId.ToInt();
            var ret = _IProductService.DeleteMenu(id, shopAdminId, out msg);
            if (ret != 1)
                return Error(msg);
            RedisManager.Remove("GetMenuList_" + shopAdminId);
            return Success(true);
        }



        /// <summary>
        /// 商品列表页面
        /// </summary>
        /// <returns></returns>
        /// 
        [ShopAuthority(AuthorityMenuEnum.ProductList)]
        public ActionResult List()
        {
            var criteria = new ProductCriteria() { PagingResult = new PagingResult(0, 15), ShopAdminId = UserContext.DeSecretId.ToInt(), OptionStatus = 999 };
            var model = GetTpageProductModel(criteria);
            var MenuList = _IProductService.MenuList(UserContext.DeSecretId.ToInt());
            MenuList = MenuList.Where(i => i.OptionStatus == 1).ToList();
            ViewBag.MenuList = MenuList;
            return View(model);
        }
        /// <summary>
        /// 条件查询商品列表
        /// </summary>
        /// <param name="criteria"></param>
        /// <returns></returns>
        [AjaxOnly]
        [HttpPost]
        [ShopAuthority(AuthorityOptionEnum.SearchList)]
        public ActionResult List(ProductCriteria criteria)
        {
            criteria.ShopAdminId = UserContext.DeSecretId.ToInt();
            var model = GetTpageProductModel(criteria);
            return PartialView("_List", model);
        }

        /// <summary>
        /// 通用获取商品列表分页模型
        /// </summary>
        /// <param name="criteria"></param>
        /// <returns></returns>
        public TPagedModelList<ProductModel> GetTpageProductModel(ProductCriteria criteria)
        {
            var query = _IProductService.ProductList(criteria);
            return new TPagedModelList<ProductModel>(query, query.PagingResult);
        }
        /// <summary>
        /// 发布商品页面
        /// </summary>
        /// <returns></returns>
        public ActionResult AddProduct()
        {
            var MenuList = _IProductService.MenuList(UserContext.DeSecretId.ToInt());
            var ships = _ISetService.GetShippingTemplateList(UserContext.DeSecretId.ToInt());
            MenuList = MenuList.Where(i => i.OptionStatus == 1).ToList();
            ViewBag.MenuList = MenuList;
            ViewBag.Ships = ships;
            return View();
        }
        /// <summary>
        /// 提交发布商品
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [AjaxOnly]
        [ShopAuthority(AuthorityOptionEnum.AddProduct)]
        public JsonResult AddProduct(ProductModel model)
        {
            if (!ModelState.IsValid)
                return Error(base.ErrorMsg());
            model.ShopAdminId = UserContext.DeSecretId.ToInt();
            #region 验证并将商品图片和详情图片传输到服务器
            if (model.BannerImgs == null || model.BannerImgs.Count <= 0)
                return Error("商品图片必传");
            //将商品图上传的图片服务器
            if (!UploadService.Upload(model.BannerImgs, UploaderKeys.ProductBanner))
                return Error("上传图片失败");
            //将商品详情的图片传到图片服务器
            if (!UploadService.Upload(model.DetailImgs, UploaderKeys.ProductDetail))
                return Error("上传图片失败");
            #endregion
            //将商品详情的图片URL替换成图片服务器路径
            //http://192.168.39.75:8068/SuperiorImages/Temp/20190109034827_106.png
            if (model.DetailImgs != null && model.DetailImgs.Count > 0)
                model.Detail = model.Detail.Replace(ConfigSettings.Instance.AdminImageHost + "/Temp", ConfigSettings.Instance.ImageServiceUrl + ProductDetailUploader.Instance.FolderName + "/" + DateTime.Now.ToString("yyyyMMdd"));
            var res = _IProductService.AddProduct(model);
            if (!res)
                return Error("发布商品失败");
            //控制redis
            RedisManager.Remove("GetHomeData_" + model.ShopAdminId);
            return Success(true);
        }

        /// <summary>
        /// 删除商品
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [AjaxOnly]
        [ShopAuthority(AuthorityOptionEnum.DeleteProduct)]
        public JsonResult DeleteProduct(string id)
        {
            string msg = "";
            int shopAdminId = UserContext.DeSecretId.ToInt();
            var ret = _IProductService.DeleteProduct(base.ValidataParms(id).ToInt(), shopAdminId, out msg);
            if (ret != 1)
                return Error(msg);
            //控制redis
            RedisManager.Remove("GetHomeData_" + shopAdminId);
            return Success(true);
        }

        /// <summary>
        /// 商品上下架
        /// </summary>
        /// <param name="id"></param>
        /// <param name="optionStatus"></param>
        /// <returns></returns>
        [AjaxOnly]
        [ShopAuthority(AuthorityOptionEnum.OptionProduct)]
        public JsonResult OptionProduct(string id, int optionStatus)
        {
            string msg = "";
            int shopAdminId = UserContext.DeSecretId.ToInt();
            var ret = _IProductService.OptionProduct(base.ValidataParms(id).ToInt(), optionStatus, shopAdminId, out msg);
            if (ret != 1)
                return Error(msg);
            //控制redis
            RedisManager.Remove("GetHomeData_" + shopAdminId);
            return Success(true);
        }

        /// <summary>
        /// 商品编辑页面
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult ProductEdit(string id)
        {
            var _id = base.ValidataParms(id);
            if (_id == null)
                return Error("请不要随意篡改参数错误");
            var model = _IProductService.GetProduct(_id.ToInt());
            var MenuList = _IProductService.MenuList(UserContext.DeSecretId.ToInt());
            var ships = _ISetService.GetShippingTemplateList(UserContext.DeSecretId.ToInt());
            MenuList = MenuList.Where(i => i.OptionStatus == 1).ToList();
            ViewBag.Ships = ships;
            ViewBag.MenuList = MenuList;
            return View(model);
        }
        /// <summary>
        /// 提交商品编辑
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [AjaxOnly]
        [ShopAuthority(AuthorityOptionEnum.ProductEdit)]
        public JsonResult ProductEdit(ProductModel model)
        {
            if (!ModelState.IsValid)
                return Error(base.ErrorMsg());
            model.ShopAdminId = UserContext.DeSecretId.ToInt();
            model.Id = base.ValidataParms(model.Id);
            #region 验证并将商品图片和详情图片传输到服务器
            if (model.BannerImgs == null || model.BannerImgs.Count <= 0)
                return Error("商品图片必传");
            //将更改后的最新的图片上传到图片服务器=》包含后台图片网关域名的
            var _bannerImgs = model.BannerImgs.Where(i => i.Contains(ConfigSettings.Instance.AdminImageHost)).ToList();
            if (!UploadService.Upload(_bannerImgs, UploaderKeys.ProductBanner))
                return Error("上传图片失败");
            //将更改后的最新的商品详情的图片传到图片服务器
            var _detailImgs = model.DetailImgs.Where(i => i.Contains(ConfigSettings.Instance.AdminImageHost)).ToList();
            if (!UploadService.Upload(_detailImgs, UploaderKeys.ProductDetail))
                return Error("上传图片失败");
            #endregion
            //将商品详情的图片URL替换成图片服务器路径
            //http://192.168.39.75:8068/SuperiorImages/Temp/20190109034827_106.png
            if (model.DetailImgs != null && model.DetailImgs.Count > 0)
                model.Detail = model.Detail.Replace(ConfigSettings.Instance.AdminImageHost + "/Temp", ConfigSettings.Instance.ImageServiceUrl + ProductDetailUploader.Instance.FolderName + "/" + DateTime.Now.ToString("yyyyMMdd"));
            var res = _IProductService.EditProduct(model);
            if (!res)
                return Error("修改商品失败");
            //控制redis
            RedisManager.Remove("GetProductDetail_" + model.Id);
            RedisManager.Remove("GetHomeData_" + model.ShopAdminId);
            return Success(true);
        }
        /// <summary>
        /// 商品sku设置页面
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult ProductSku(string id)
        {
            var shopAdminId = UserContext.DeSecretId.ToInt();
            var _id = base.ValidataParms(id);
            if (_id == null)
                return Error("请不要随意篡改参数错误");
            var model = _IProductService.GetProductSkuManagerModel(shopAdminId, _id);
            return View(model);
        }
        /// <summary>
        /// 获取多规格数据业务模型
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// 
        [AjaxOnly]
        public JsonResult GetMoreSkuManager(string id)
        {
            var shopAdminId = UserContext.DeSecretId.ToInt();
            var _id = base.ValidataParms(id);
            if (_id == null)
                return Error("请不要随意篡改参数错误");
            var model = _IProductService.GetProductSkuManagerModel_AJAX(shopAdminId, _id);
            return Success(model);
        }
        /// <summary>
        /// 提交商品单规格数据
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [AjaxOnly]
        [ShopAuthority(AuthorityOptionEnum.EditSingleSku)]
        public JsonResult EditSingleSku(SingleSkuModel model)
        {
            if (!ModelState.IsValid)
                return Error(base.ErrorMsg());
            model.ShopAdminId = UserContext.DeSecretId.ToInt();
            model.ProductId = base.ValidataParms(model.ProductId);
            model.SkuCode = model.SkuCode == null ? "" : model.SkuCode;
            var ret = _IProductService.EditSingleSku(model);
            if (!ret)
                return Error("提交失败");
            RedisManager.Remove("GetHomeData_" + model.ShopAdminId);
            return Success(true);
        }
        /// <summary>
        /// 多规格提交
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [AjaxOnly]
        [ShopAuthority(AuthorityOptionEnum.EditMoreSku)]
        public JsonResult EditMoreSku(ProductSkuManagerModel model)
        {
            if (!ModelState.IsValid)
                return Error(base.ErrorMsg());
            var shopAdminId = UserContext.DeSecretId.ToInt();
            model.ProductId = base.ValidataParms(model.ProductId);
            var ret = _IProductService.EditMoreSku(model, shopAdminId);
            if (!ret)
                return Error("提交失败");
            RedisManager.Remove("GetHomeData_" + shopAdminId);
            return Success(true);
        }

        /// <summary>
        /// 多规格下，添加属性
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        /// 
        [HttpPost]
        [AjaxOnly]
        [ShopAuthority(AuthorityOptionEnum.AddPropety)]
        public JsonResult AddPropety(AddPropetyParamsModel model)
        {
            if (!ModelState.IsValid)
                return Error(base.ErrorMsg());
            model.ShopAdminId = UserContext.DeSecretId.ToInt();
            model.ProductId = base.ValidataParms(model.ProductId);
            string msg = "";
            var ret = _IProductService.AddPropety(model, out msg);
            if (ret != 1)
                return Error(msg);
            return Success(true);
        }
        /// <summary>
        /// 追加规格值
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        /// 
        [HttpPost]
        [AjaxOnly]
        [ShopAuthority(AuthorityOptionEnum.AddPropetyValue)]
        public JsonResult AddPropetyValue(Product_Sall_Propety_ValueModel model)
        {
            if (string.IsNullOrEmpty(model.PropetyValue))
                return Error("规格值不能为空");
            model.ProductId = base.ValidataParms(model.ProductId);
            string msg = "";
            var ret = _IProductService.AddPropetyValue(model, out msg);
            if (ret != 1)
                return Error(msg);
            return Success(true);
        }
        /// <summary>
        /// 删除整个规格属性
        /// </summary>
        /// <param name="id"></param>
        /// <param name="productId"></param>
        /// <returns></returns>
        [AjaxOnly]
        [ShopAuthority(AuthorityOptionEnum.DelPropety)]
        public JsonResult DelPropety(int id, string productId)
        {
            productId = base.ValidataParms(productId);
            var shopAdminId = UserContext.DeSecretId.ToInt();
            var ret = _IProductService.DelPropety(id, productId, shopAdminId);
            if (!ret)
                return Error("删除失败");
            return Success(true);
        }
        /// <summary>
        /// 删除规格值
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [AjaxOnly]
        [ShopAuthority(AuthorityOptionEnum.DelPropetyValue)]
        public JsonResult DelPropetyValue(Product_Sall_Propety_ValueModel model)
        {
            model.ProductId = base.ValidataParms(model.ProductId);
            var ret = _IProductService.DelPropetyValue(model);
            if (!ret)
                return Error("删除失败");
            return Success(true);
        }
        /// <summary>
        /// 首页轮播图管理
        /// </summary>
        /// <returns></returns>
        /// 
        [ShopAuthority(AuthorityMenuEnum.ProductBannerList)]
        public ActionResult BannerList()
        {
            var model = _IProductService.GetProductBannerList(UserContext.DeSecretId.ToInt());
            return View(model);
        }
        public ActionResult AddBanner()
        {
            return View();
        }
        public ActionResult EditBanner(int id)
        {
            var model = _IProductService.GetProductBanner(id);
            return View(model);
        }

        /// <summary>
        /// 提交首页轮播图
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [AjaxOnly]
        [ShopAuthority(AuthorityOptionEnum.AddBanner)]
        public JsonResult AddBanner(ProductBannerModel model)
        {
            if (!ModelState.IsValid)
                return Error(base.ErrorMsg());
            model.ShopAdminId = UserContext.DeSecretId.ToInt();

            //将商品图上传的图片服务器
            if (!UploadService.Upload(model.ImgPath, UploaderKeys.ProductBanner))
                return Error("上传图片失败");
            model.ProductId = SecretClass.DecryptQueryString(model.ProductId);
            var res = _IProductService.AddProductBanner(model);
            if (!res)
                return Error("提交轮播图失败");
            //控制redis
            RedisManager.Remove("GetHomeData_" + model.ShopAdminId);
            return Success(true);
        }
        /// <summary>
        /// 编辑首页轮播图
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [AjaxOnly]
        [ShopAuthority(AuthorityOptionEnum.EditBanner)]
        public JsonResult EditBanner(ProductBannerModel model)
        {
            if (!ModelState.IsValid)
                return Error(base.ErrorMsg());
            model.ShopAdminId = UserContext.DeSecretId.ToInt();
            //如果图片地址包括后台网关，就从新上传
            if (model.ImgPath.Contains(ConfigSettings.Instance.AdminImageHost))
            {
                if (!UploadService.Upload(model.ImgPath, UploaderKeys.ProductBanner))
                    return Error("上传图片失败");
            }
            model.ProductId = SecretClass.DecryptQueryString(model.ProductId);
            var res = _IProductService.EditProductBanner(model);
            if (!res)
                return Error("修改轮播图失败");
            //控制redis
            RedisManager.Remove("GetHomeData_" + model.ShopAdminId);
            return Success(true);
        }
        /// <summary>
        /// 操作轮播图上下架
        /// </summary>
        /// <param name="id"></param>
        /// <param name="optionStatus"></param>
        /// <returns></returns>
        [AjaxOnly]
        [ShopAuthority(AuthorityOptionEnum.OptionBanner)]
        public JsonResult OptionBanner(int id, int optionStatus)
        {
            _IProductService.OptionProductBanner(id, optionStatus);
            //控制redis
            RedisManager.Remove("GetHomeData_" + UserContext.DeSecretId);
            return Success(true);
        }
        /// <summary>
        /// 删除轮播图
        /// </summary>
        /// <param name="id"></param>
        /// <param name="optionStatus"></param>
        /// <returns></returns>
        [AjaxOnly]
        [ShopAuthority(AuthorityOptionEnum.DelBanner)]
        public JsonResult DelBanner(int id)
        {
            _IProductService.DelProductBanner(id);
            //控制redis
            RedisManager.Remove("GetHomeData_" + UserContext.DeSecretId);
            return Success(true);
        }
        /// <summary>
        /// 商品专场列表
        /// </summary>
        /// <returns></returns>
        [ShopAuthority(AuthorityMenuEnum.SpecialPlace)]
        public ActionResult SpecialList()
        {
            var shopAdminId = UserContext.DeSecretId.ToInt();
            var list = _IProductService.SpecialPlaceList(shopAdminId);
            return View(list);
        }
        /// <summary>
        /// 删除专场
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// 
        [ShopAuthority(AuthorityOptionEnum.DeleteSepecial)]
        [AjaxOnly]
        public JsonResult DelSpecial(int id)
        {
            _IProductService.DelSpecialPlace(id);
            RedisManager.Remove("SpecialPlaceList" + UserContext.DeSecretId + "_1");
            RedisManager.Remove("SpecialPlaceList" + UserContext.DeSecretId + "_2");
            return Success(true);
        }

        /// <summary>
        /// 商品专场添加或编辑
        /// </summary>
        /// <returns></returns>
        /// 
        [ShopAuthority(AuthorityMenuEnum.SpecialPlace)]
        public ActionResult SpecialPlace(int id = 0)
        {
            var model = new SpecialPlaceModel();
            if (id > 0)
                model = _IProductService.GetSpecialPlaceModel(id);
            var MenuList = _IProductService.MenuList(UserContext.DeSecretId.ToInt());
            MenuList = MenuList.Where(i => i.OptionStatus == 1).ToList();
            ViewBag.MenuList = MenuList;
            return View(model);
        }
        /// <summary>
        /// 添加或更改专场
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [AjaxOnly]
        [HttpPost]
        [ShopAuthority(AuthorityOptionEnum.OptionSpecialPlace)]
        public JsonResult OptionSpecialPlace(SpecialPlaceModel model)
        {
            if (!ModelState.IsValid)
                return Error(base.ErrorMsg());
            model.ShopAdminId = UserContext.DeSecretId.ToInt();
            if (model.Id == 0)
            {
                //将商品图上传的图片服务器
                if (!UploadService.Upload(model.ImgPath, UploaderKeys.ProductMenu))
                    return Error("上传图片失败");
            }
            else
            {
                //如果图片地址包括后台网关，就从新上传
                if (model.ImgPath.Contains(ConfigSettings.Instance.AdminImageHost))
                {
                    if (!UploadService.Upload(model.ImgPath, UploaderKeys.ProductMenu))
                        return Error("上传图片失败");
                }
            }
            var ret = _IProductService.InsertOrEditSpecialPlace(model);
            if (!ret)   
                return Error("操作失败");

            RedisManager.Remove("SpecialPlaceList" + model.ShopAdminId + "_1");
            RedisManager.Remove("SpecialPlaceList" + model.ShopAdminId + "_2");
            return Success(true);
        }



    }
}